import DatePicker from "components/antd-compatible/date-picker";
/**
 * Created by tanbingqin on 2019/12/18.
 */
import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import errorMessage from 'share/errorMessage';
import menuRoute from 'routes/menuRoute'
import { message, Button, Popconfirm, Icon, Form, Input, Row, Col,  Select, Spin, Checkbox } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import moment from 'moment';
import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import debounce from 'lodash.debounce'
import MultiSelector from 'components/template/multi-selector'

class NewProxy extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      fetching: false,
      personList: [], //代理人可选范围列表
      validateStatus: '', //代理人校验的status
      validateMessage: '', //代理人校验的message
      startDate: moment(new Date()),
      endDate: null
    };
    this.searchValue = debounce(this.searchValue, 250);
  }

  componentDidMount() {
    const { record } = this.props;
    const { setFieldsValue } = this.props.form;
    if (record) {
      let chosenExpense = [];
      let chosenRequest = [];
      let chosenLoan = [];
      let chosenCommon = [];
      record.customFormDTOs && record.customFormDTOs.map(item => {
        if (item.entityType === 1002) {  //报销单
          chosenExpense.push({formOID: item.formOID, formName: item.formName});
        } else if (item.entityType === 1001) {  //申请单
          chosenRequest.push({formOID: item.formOID, formName: item.formName});
        } else if (item.entityType === 3001) {  //借款单
          chosenLoan.push({formOID: item.formOID, formName: item.formName});
        } else if (item.entityType === 4001) {  //通用表单
          chosenCommon.push({formOID: item.formOID, formName: item.formName});
        }
      });
      //处理代理人数据
      let personInfo = {
        fullName: record.proxyName,
        userOID: record.proxyOID,
        emplyeeId: record.emplyeeId,
        leavingDate: record.leavingDate,
        status: record.status,
        text: `${record.proxyName} - ${record.emplyeeId}`
      };
      setFieldsValue({
        chosenExpense,
        chosenRequest,
        chosenLoan,
        chosenCommon,
        isCheckAll: record.proxyFormScope === 1001,
        person: JSON.stringify(personInfo)
      });
      this.setState({
        personList: [personInfo],
        startDate: moment(record.startDate),
        endDate: record.endDate ? moment(record.endDate) : null
      });
      this.validateValue(JSON.stringify(personInfo));
    }
  }

  searchValue = (value) => {
    const { principalInfo } = this.props;
    value && this.setState({
      fetching: true
    });
    let params = {
      page: 0,
      size: 1000,
      keyword: value,
      roleType: 'TENANT'
    };
    value && value.length && agencyService.getPersonByValueV2(params).then(res => {
      let resultData = [];
      let data = res.data;
      data.map(item => {
        item.text = `${item.fullName} - ${item.employeeID}`;
        //只支持工号和姓名搜索，手机和邮箱要去除
        if (item.text.toLowerCase().indexOf(value.toLowerCase()) > -1 || item.text.toUpperCase().indexOf(value.toUpperCase()) > -1) {
          let proxyIsExist = false;
          principalInfo.billProxyRuleDTOs && principalInfo.billProxyRuleDTOs.map(proxyItem => {
            item.userOID === proxyItem.proxyOID && (proxyIsExist = true);
          });
          //移除已选过的代理人以及该代理关系的被代理人
          if (item.userOID !== principalInfo.principalOID && !proxyIsExist) {
            resultData.push(item);
          }
        }
      });
      this.setState({ personList: resultData, fetching: false });
    });
  };

  onBlur = () => {
    const { getFieldValue, setFieldsValue } = this.props.form;
    const { personList } = this.state;
    let isExist = false;
    let userOID = '';
    if (getFieldValue("person")) {
      let personInfo = JSON.parse(getFieldValue("person"));
      userOID = personInfo.userOID;
    }
    personList && personList.forEach(user => {
      if (user.userOID === userOID) {
        isExist = true;
      }
    });
    if (!isExist) {
      setFieldsValue({
        person: undefined
      });
      this.setState({
        validateStatus: 'error',
        validateMessage: messages('common.select')/*请选择*/
      });
    }
  };

  onCancel = () => {
    this.props.close();
  };

  //开始代理日期 <= 结束代理日期
  disabledStartDate = (current) => {
    const { endDate } = this.state;
    return moment(current).isAfter(moment(endDate), 'day');
  };

  //结束代理日期 >= 开始代理日期 且 结束代理日期 >= 今天
  disabledEndDate = (current) => {
    const { startDate } = this.state;
    return moment(current).isBefore(moment(startDate), 'day') || moment(current).isBefore(moment(new Date()), 'day');
  };

  getProxyOID = () => {
    const { getFieldValue } = this.props.form;
    if (getFieldValue('person')) {
      let personInfo = JSON.parse(getFieldValue('person'));
      return personInfo.userOID;
    }
    return '';
  };

  handleChange = (value) => {
    this.validateValue(value);
    this.resetChosen();
  };

  //校验代理人控件
  validateValue = (value) => {
    const { tab } = this.props;
    let errorMsg = '';
    if (value) {
      let personInfo = JSON.parse(value);
      let leaveTime = moment(personInfo.leavingDate).format('YYYY-MM-DD');
      if (personInfo.status === 1002) {
        errorMsg = messages('request-3.key60',{arg1: leaveTime})/*该员工将于 {arg1} 离职*/ +
          `${tab === 'apply' ? messages('request-3.key61')/*，离职后此代理将自动禁用*/ : ''}`;
        this.setState({validateStatus: 'warning'});
      } else if (personInfo.status === 1003) {
        errorMsg = messages('request-3.key62',{arg1: leaveTime})/*该员工已于 {arg1} 离职*/;
        this.setState({validateStatus: 'warning'});
      } else {
        errorMsg = '';
        this.setState({validateStatus: ''});
      }
    } else {
      errorMsg = messages('common.select')/*请选择*/;
      this.setState({validateStatus: 'error'});
    }
    this.setState({validateMessage: errorMsg});
  };

  //修改代理人了要重置所选表单
  resetChosen = () => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({
      isCheckAll: true,
      chosenExpense: [],
      chosenRequest: [],
      chosenLoan: [],
      chosenCommon: []
    });
  };

  handleSave = () => {
    const { startDate, endDate, validateStatus } = this.state;
    const { getFieldsValue } = this.props.form;
    const { tab, principalInfo, record, close } = this.props;
    //这里就很神奇，validateFieldsAndScroll原来的代码validateStatus在warning的情况下会没有err，但是这次新代码在warning情况下会跑进err
    //既然err不准，自己校验吧，日期不用校验，只需校验代理人和选择单据
    //找到原因了：是校验写在rules里的validator，如果只是修改validateStatus，并不会被validateFieldsAndScroll检测到
    let values = getFieldsValue();
    //校验代理人
    if (!values.person) {
      this.setState({
        validateStatus: 'error',
        validateMessage: messages('common.select')/*请选择*/
      });
      return;
    }
    //校验选择单据
    if (!values.isCheckAll && !values.chosenExpense.length && !values.chosenRequest.length && !values.chosenLoan.length && (values.chosenCommon ? !values.chosenCommon.length : true)) {
      message.error(messages('request-3.key104')/*请选择单据*/);
      return;
    }

    let customFormDTOs = [];
    if (!values.isCheckAll) {
      customFormDTOs.push(...values.chosenExpense);
      customFormDTOs.push(...values.chosenRequest);
      customFormDTOs.push(...values.chosenLoan);
      if (values.chosenCommon) {
        customFormDTOs.push(...values.chosenCommon);
      }
    }
    let personInfo = JSON.parse(values.person);
    let billProxyRuleDTO = {
      enabled: record ? record.enabled : true,
      ruleOID: record ? record.ruleOID : undefined,
      endDate: endDate ? moment(endDate).format('YYYY-MM-DD') : null,
      startDate: moment(startDate).format('YYYY-MM-DD'),
      proxyTimeRange: endDate ? 102 : 101, //proxyTimeRange: 101(无限制)、 102(自定义结束时间)
      leavingDate: personInfo.leavingDate,
      proxyName: personInfo.fullName,
      proxyOID: personInfo.userOID,
      status: personInfo.status,  //status: 1001(正常)、 1002(待离职)、1003(已离职)
      customFormDTOs: values.isCheckAll ? [] : customFormDTOs,
      proxyFormScope: values.isCheckAll ? 1001 : 1002,
      emplyeeId: personInfo.employeeID || personInfo.employeeId || personInfo.emplyeeId,
      proxyOperationType: tab === 'apply' ? 1 : 2
    };
    let billProxyRuleDTOs = principalInfo.billProxyRuleDTOs || [];
    principalInfo.enabled = false;
    let isExist = false;
    billProxyRuleDTOs.map((item, index) => {
      if (item.ruleOID === billProxyRuleDTO.ruleOID) {
        isExist = true;
        billProxyRuleDTOs[index] = billProxyRuleDTO;
      }
    });
    //新建
    if (!isExist) {
      billProxyRuleDTOs.push(billProxyRuleDTO);
    }
    billProxyRuleDTOs.map(item => {
      item.enabled && (principalInfo.enabled = true);
    });
    principalInfo.billProxyRuleDTOs = billProxyRuleDTOs;
    this.setState({ loading: true });
    agencyService.newAgency(principalInfo).then(res => {
      message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
      this.setState({ loading: false });
      close(true);
    }).catch(e => {
      this.setState({ loading: false });
      errorMessage(e.response);
    });
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { loading, fetching, personList, validateStatus, startDate, endDate, validateMessage } = this.state;
    const { tab, principalInfo, record } = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16, offset: 1}
    };
    return (
      <div className="new-form">
        <Form>
          <FormItem
            {...formItemLayout}
            label={messages('request-3.key27')/*代理人*/}
            validateStatus={validateStatus}
            help={validateMessage}
            extra={tab === 'apply' ? messages('request-3.key57')/*选择哪些员工可以帮被代理人提交单据，单据可按照被代理人的需求进行分配*/ :
              messages('request-3.key58')/*选择哪些员工可以帮被代理人审批单据，单据可按照被代理人的需求进行分配*/
            }
          >
            {getFieldDecorator('person', {
              rules: [
                {
                  required: true
                }
              ]
            })(
              <Select
                placeholder={messages('request-3.key63')/*请输入姓名/工号*/}
                allowClear
                showSearch
                filterOption={false}
                notFoundContent={fetching ? <Spin size="small" /> : messages('common.unmatched')/*无匹配结果*/}
                onSearch={this.searchValue}
                onBlur={this.onBlur}
                onChange={this.handleChange}
                getPopupContainer={triggerNode => triggerNode.parentNode}
                disabled={!!record}
              >
                {personList.map(d => <Option key={JSON.stringify(d)}>{d.text}</Option>)}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-3.key7')/*代理日期*/}>
            <DatePicker
              format="YYYY-MM-DD"
              value={startDate}
              allowClear={false}
              disabledDate={this.disabledStartDate}
              onChange={date => this.setState({startDate: date})}
              style={{width: 'auto'}}
            />
            <span>&nbsp;&nbsp;{messages('request-3.key48')/*至*/}&nbsp;&nbsp;</span>
            <DatePicker
              format="YYYY-MM-DD"
              value={endDate}
              placeholder={messages('request-3.key13')/*无限制*/}
              disabledDate={this.disabledEndDate}
              onChange={date => this.setState({endDate: date})}
              style={{width: 'auto'}}
            />
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-3.key8')/*代理单据*/}>
            {getFieldDecorator('isCheckAll', {
              valuePropName: 'checked',
              initialValue: true
            })(
              <Checkbox>{messages('common.all')/*全部*/}</Checkbox>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-3.key30')/*报销单*/}>
            {getFieldDecorator('chosenExpense', {
              initialValue: []
            })(
              <MultiSelector
                type="proxy_form_admin"
                params={{
                  customFormType: 1002,
                  operationCode: tab === 'apply' ? 1 : 2,
                  principalOID: principalInfo.principalOID,
                  proxyOID: this.getProxyOID()
                }}
                isShowSelectAll
                disabled={getFieldValue('isCheckAll')}
                isAll={getFieldValue('isCheckAll')}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-3.key31')/*申请单*/}>
            {getFieldDecorator('chosenRequest', {
              initialValue: []
            })(
              <MultiSelector
                type="proxy_form_admin"
                params={{
                  customFormType: 1001,
                  operationCode: tab === 'apply' ? 1 : 2,
                  principalOID: principalInfo.principalOID,
                  proxyOID: this.getProxyOID()
                }}
                isShowSelectAll
                disabled={getFieldValue('isCheckAll')}
                isAll={getFieldValue('isCheckAll')}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-3.key32')/*借款单*/}>
            {getFieldDecorator('chosenLoan', {
              initialValue: []
            })(
              <MultiSelector
                type="proxy_form_admin"
                params={{
                  customFormType: 3001,
                  operationCode: tab === 'apply' ? 1 : 2,
                  principalOID: principalInfo.principalOID,
                  proxyOID: this.getProxyOID()
                }}
                isShowSelectAll
                disabled={getFieldValue('isCheckAll')}
                isAll={getFieldValue('isCheckAll')}
              />
            )}
          </FormItem>
          {tab === 'approve' &&
            <FormItem {...formItemLayout} label={messages('request-3.key105')/*通用表单*/}>
              {getFieldDecorator('chosenCommon', {
                initialValue: []
              })(
                <MultiSelector
                  type="proxy_form_admin"
                  params={{
                    customFormType: 4001,
                    operationCode: tab === 'apply' ? 1 : 2,
                    principalOID: principalInfo.principalOID,
                    proxyOID: this.getProxyOID()
                  }}
                  isShowSelectAll
                  disabled={getFieldValue('isCheckAll')}
                  isAll={getFieldValue('isCheckAll')}
                />
              )}
            </FormItem>
          }
        </Form>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={loading}>{messages('common.ok')/*确定*/}</Button>
          <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps() {
  return {}
}

NewProxy.propTypes = {};

NewProxy.defaultProps = {};

const WrappedNewProxy = Form.create()(NewProxy);

export default connect(mapStateToProps)(WrappedNewProxy);
